from typing import Union

from fastapi import FastAPI, status

from gacha_simulator.core.entities import GachaStatsData, GachaWishData, ResponseData
from gacha_simulator.core.gacha import GachaSimulator
from gacha_simulator.core.gacha_history import GachaHistory, GachaItem

app = FastAPI()


@app.post("/wish", response_model=ResponseData)
def wish(post_body: GachaWishData):
    simulator = GachaSimulator(post_body.user_id)
    wish_result = simulator.wish(post_body.count)
    summary = ''
    if post_body.count == 1:
        rarity = wish_result[0].rarity
        if rarity == 5:
            summary = '哇！单抽出金了！又是欧气满满的一天！'
        elif rarity == 4:
            summary = '单抽出紫，不亏！'
        else:
            summary = '平凡也是一种幸福！'
    if post_body.count == 10:
        five_star_count: int = 0
        four_star_count: int = 0
        for item in wish_result:
            if item.rarity == 5:
                five_star_count += 1
            elif item.rarity == 4:
                four_star_count += 1
        if five_star_count > 1:
            summary = '原来你就是万里挑一的超级无敌大欧皇？！！'
        elif five_star_count == 1:
            summary = '好耶！金光闪闪！'
        elif four_star_count > 1:
            summary = '运气不错哦！'
        else:
            summary = '平凡也是一种幸福！'
    return ResponseData(code=status.HTTP_200_OK, message='OK', data={
        'summary': summary,
        'items': [
            { '名称': gacha_item.name, '稀有度（星级）': '★' * gacha_item.rarity } for gacha_item in wish_result
        ]
    })


@app.post('/stats', response_model=ResponseData)
def get_wish_history_stats(post_body: GachaStatsData):
    simulator = GachaSimulator(post_body.user_id)
    history = GachaHistory.read_history(post_body.user_id)
    sunk_cost_ssr: int = history.get('sunk_cost_ssr', 0)
    sunk_cost_sr: int = history.get('sunk_cost_sr', 0)
    is_guaranteed: bool = history.get('is_guaranteed', False)
    history_items: list[GachaItem] = history.get('history_items', [])
    up_avg = get_up_avg(history_items, simulator.banner_character)
    if up_avg is None:
        up_avg = '暂未抽到概率 Up 角色'
    five_star_avg = get_ssr_avg(history_items)
    if five_star_avg is None:
        five_star_avg = '暂未抽到五星角色'
    four_star_avg = get_sr_avg(history_items)
    if four_star_avg is None:
        four_star_avg = '暂未抽到四星角色'
    return ResponseData(code=status.HTTP_200_OK, message='OK', data={
        '距离上一个五星角色': sunk_cost_ssr,
        '距离上一个四星角色': sunk_cost_sr,
        '保底状态': '大保底' if is_guaranteed else '小保底',
        '概率 Up 角色平均抽数': up_avg,
        '五星角色平均抽数': five_star_avg,
        '四星角色平均抽数': four_star_avg
    })


def get_up_avg(items: list[GachaItem], up: str) -> Union[float, None]:
    if not items:
        return None
    up_counts: list[int] = []
    count: int = 0
    for gacha_item in items:
        count += 1
        if gacha_item.name == up:
            up_counts.append(count)
            count = 0
    if not up_counts:
        return None
    return sum(up_counts) / len(up_counts)


def get_ssr_avg(items: list[GachaItem]) -> Union[float, None]:
    if not items:
        return None
    ssr_counts: list[int] = []
    count: int = 0
    for gacha_item in items:
        count += 1
        if gacha_item.rarity == 5:
            ssr_counts.append(count)
            count = 0
    if not ssr_counts:
        return None
    return sum(ssr_counts) / len(ssr_counts)


def get_sr_avg(items: list[GachaItem]) -> Union[float, None]:
    if not items:
        return None
    sr_counts: list[int] = []
    count: int = 0
    for gacha_item in items:
        count += 1
        if gacha_item.rarity == 4:
            sr_counts.append(count)
            count = 0
    if not sr_counts:
        return None
    return sum(sr_counts) / len(sr_counts)
